package com.example.myapplication.utils;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleOwner;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by ymz0427 on 2021/10/23
 */
class RunnableObserver implements LifecycleEventObserver {

    private final List<LifecycleRunnable> list = new ArrayList<>();

    private Map<Lifecycle, RunnableObserver> map;

    public RunnableObserver(Map<Lifecycle, RunnableObserver> map) {
        this.map = map;
    }

    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
        if (event == Lifecycle.Event.ON_DESTROY) {
            //生命周期监听移除
            source.getLifecycle().removeObserver(this);
            //当LifecycleOwner销毁时，将<Lifecycle,RunnableObserver>键值对移除
            map.remove(source.getLifecycle());
            map = null;
            //销毁时清空所有相关的Runnable
            for (LifecycleRunnable tmp : list) {
                tmp.clean();
            }
            list.clear();
        }
    }

    void add(LifecycleRunnable runnable) {
        list.add(runnable);
    }

    void remove(LifecycleRunnable runnable) {
        list.remove(runnable);
        runnable.clean();
    }
}
